// pages/chooseClient/chooseClient.js
import * as API from '../../../api/myShareApi';
import * as util from '../../../utils/util';

let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    placeholder: '输入客户名称/手机号搜索',
    searchKey: '',
    id: '',
    name: '',
    pageNo: 1,
    pageSize: 10,
    hasRequest: false,
    networkError: false,
    dataSource: [],
    total: 0,
    checkedAll: false,
    checkedNum: 0,
    customId: '',
    customName: '',
    from: '',
    isAdmin: false
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (options) {
    this.loadData(true);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(app.globalData.user)
    this.setData({
      customId: options.customId,
      customName: options.customName,
      // isAdmin: app.globalData.user.isAdmin || false,
      from: options.from || ''
    })
    this.clear();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 加载数据
   */
  loadData: function (options) {
    let choosedClient = wx.getStorageSync('choosedClient');
    const postbody = {
      pageNo: this.data.pageNo,
      pageSize: this.data.pageSize,
      searchKey: this.data.searchKey || '',
      // shardingId: app.globalData.user && app.globalData.user.currentShardingId,
      shardingId: choosedClient.shardingId,
      customId: this.data.customId
    };
    API.msgSendContactsList(postbody).then(res => {
      let arr = res.customAccountList;
      if (arr.length > 0) {
        this.setData({
          networkError: false
        })
      } else {
        this.setData({
          networkError: true
        })
      }
      if (!options) {
        // arr = this.data.dataSource.concat(res.customAccountList || []);
        arr = util.deepClone(this.data.dataSource);
        res.customAccountList.map((item) => {
          arr.push(item);
        })
      }
      let hasMore = arr.length < res.totalCount;
      if (wx.getStorageSync('choosedContacts')) {
        const cachedData = wx.getStorageSync('choosedContacts');
        arr.map(el => {
          cachedData.forEach(element => {
            if (el.id == element.id) {
              el.checked = element.checked
            }
          });
          // return el;
        })
        this.setData({
          checkedAll: res.totalCount == cachedData.length,
          dataSource: arr,
          hasRequest: true,
          total: res.totalCount
        })
      } else {
        this.setData({
          dataSource: arr,
          hasRequest: true,
          total: res.totalCount

        });
      }
    }, err => {

    })
  },

  /**
   * 点击单选
   */
  toggleCheck: function (e) {
    //將選擇訂單加入緩存中
    var choosedContacts = []
    for (let i in wx.getStorageSync('choosedContacts')) {
      choosedContacts.push(wx.getStorageSync('choosedContacts')[i]); //属性
      //arr.push(obj[i]); //值
    }
    var choosedContactsIds = choosedContacts.map(el => el.id);
    if (e.currentTarget && e.currentTarget.dataset.list) {
      let data = this.data.dataSource.map(el => {
        if (el.id == e.currentTarget.dataset.list.id) {
          el.checked = !el.checked;
        }
        if (choosedContactsIds.indexOf(el.id) >= 0 && !el.checked) {
          //如果在缓存中却没有勾选就将该订单移除出去缓存列表
          var index = choosedContactsIds.indexOf(el.id);
          choosedContacts.splice(index, 1);
        } else if (choosedContactsIds.indexOf(el.id) < 0 && el.checked) {
          //如果不在缓存中确已经选择了,那么加入缓存列表
          choosedContacts.push(el)
        }
        return el;
      })
      const num = data.filter(el => el.checked).length;
      this.setData({
        dataSource: data,
        checkedNum: choosedContacts.length,
        // checkedAll: choosedContacts.length == this.data.dataSource.length   方案1
        checkedAll: 1 > choosedContacts.length
      })
      wx.setStorageSync('choosedContacts', choosedContacts);
    }

  },

  /**
   * 方案1
   * 切换全选
   */
  // toggleAll: function () {
  //   var choosedContacts = []
  //   for (let i in wx.getStorageSync('choosedContacts')) {
  //     choosedContacts.push(wx.getStorageSync('choosedContacts')[i]); //属性
  //     //arr.push(obj[i]); //值
  //   }
  //   var choosedContactsIds = choosedContacts.map(el => el.id);

  //   let status = !this.data.checkedAll;
  //   let data = this.data.dataSource.map(el => {
  //     el.checked = status;
  //     if (!status) {
  //       //如果勾选状态为取消
  //       choosedContacts = []
  //     } else if (status && choosedContactsIds.indexOf(el.id) < 0) {
  //       //如果勾选状态为全选,而且订单不存在缓存中,那么加入缓存
  //       choosedContacts.push(el);
  //     }
  //     return el;
  //   })
  //   this.setData({
  //     dataSource: data,
  //     checkedAll: status,
  //     checkedNum: status ? choosedContacts.length : 0
  //   });
  //   wx.setStorage({
  //     key: 'choosedContacts',
  //     data: choosedContacts,
  //   });
  // },

  /**
   * 清空选择
   */
  toggleAll: function () {
    let data = this.data.dataSource.map(el => {
      el.checked = false;
      return el;
    })
    this.setData({
      dataSource: data,
      checkedAll: false,
      checkedNum: 0
    });
    wx.setStorageSync('choosedContacts', []);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    // 增量加载
    var hasMore = this.data.dataSource.length < this.data.total;
    //debugger
    if (hasMore) {
      this.setData({
        pageNo: ++this.data.pageNo
      });
      this.loadData(false);
    }
  },

  clear: function () {
    this.setData({
      dataSource: [],
      pageNo: 1,
      pageSize: 10,
    })
  },

  clearSearch: function () {
    this.setData({
      searchKey: '',
      pageNo: 1,
      pageSize: 10,
      hasMore: true,
      dataSource: [],
    });
    this.loadData(true);
  },

  onHandleSearch(e) {
    this.setData({
      searchKey: e.detail
    });
    this.loadData(true);
  },

  /**
   * 发送请求并清除storage
   */
  sendData(postbody) {
    API.messageSend(postbody).then(res => {
      // let str = '发送成功' + res.successCount + "个,发送失败" + res.failCount + "个"
      wx.removeStorageSync('sharedData');
      wx.hideLoading();
      // util.toast(str);
      // setTimeout(() => {
      wx.navigateTo({
        url: '/pages/shortMsg/sendSuccess/sendSuccess'
      });
      // }, 700)

    }, err => {
      wx.removeStorage('sharedData')
      wx.hideLoading();
      util.toast('发送短信失败');
      setTimeout(() => {
        wx.navigateBack({});
      }, 600)
      // wx.showToast({
      //   title: err,
      //   icon: 'none'
      // });
    });
  },

  /**
   * 点击完成
   */
  ensure: function () {
    if (this.data.checkedNum !== 0) {
      wx.showLoading({
        title: '推送中',
      });
      let choosedClient = wx.getStorageSync('choosedClient');
      let sharedData = wx.getStorageSync('sharedData');
      const orderIds = sharedData.map(el => ({
        orderid: el.id,
        hiddenPrice: el.hiddenPrice
      }));
      const telephoneIds = this.data.dataSource.filter(el => el.checked).map(el => ({
        telephone: el.telephone
      }));
      let postbody = {
        customCode: choosedClient.code,
        customId: choosedClient.id,
        customName: choosedClient.name,
        orderList: orderIds,
        telephoneList: telephoneIds,
        from: this.data.from
      };

      this.sendData(postbody);

    } else {
      wx.showToast({
        title: '请选择客户',
        icon: 'none'
      });
      return;
    }
  },

  gotoAdd: function () {
    util.toast('体验环境不可用');
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    wx.removeStorageSync('choosedContacts')
  },
})